/**
 * 
 */
package co.com.ebusiness.trader.pages;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.BeanEditForm;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.Session;

import co.com.ebusiness.trader.core.model.Empresa;
import co.com.ebusiness.trader.model.Venta;
import co.com.ebusiness.trader.seguridad.model.Usuario;
import co.com.ebusiness.trader.seguridad.model.UsuarioEmpresa;
import co.com.ebusiness.trader.services.TraderService;

/**
 * @author Luis Agudelo
 *
 */
public class ActualizarVenta {

	
		// Screen fields
		@Property
		private Venta venta;
		
		// Other pages
		@InjectPage
		private VentaDiaria indexPage;

		// Generally useful bits and pieces

		@Component(id = "ventaForm")
		private BeanEditForm ventaForm;

		@Inject
		private TraderService traderService;
		
		@Inject
	 	private Request request;

		
		// onPassivate() is called by Tapestry to get the activation context to put in the URL.

		Venta onPassivate() {
			return venta;
		}
		
		// onActivate() is called by Tapestry to pass in the activation context from the URL.
		void onActivate(Venta venta) {
			this.venta = venta;
		}

		// PersonForm bubbles up the PREPARE_FOR_SUBMIT event during form submission.
		void onPrepareForSubmit() {
			// Get objects for the form fields to overlay.
			venta = traderService.getVenta(venta.getIdVent());
			
			if (venta == null) {
				venta = new Venta();
				ventaForm.recordError("La venta ha sido borrada.");
			}
		}

		// PersonForm bubbles up the VALIDATE event when it is submitted
		@CommitAfter
		void onValidateFromVentaForm() {

			if (ventaForm.getHasErrors()) {
				// We get here only if a server-side validator detected an error.
				return;
			}

			try {
				Session session = request.getSession(false);
				Empresa empresa = null;
				Usuario usuario = null;
				if (session != null && session.getAttribute("state:Index::empresa") != null){
					empresa = ((UsuarioEmpresa)session.getAttribute("state:Index::empresa")).getEmpresa();
					usuario = ((UsuarioEmpresa)session.getAttribute("state:Index::empresa")).getUsuario();
		 		}
				venta.setEmpresa(empresa);
				venta.setUsuario(usuario);
				
				traderService.guardarVenta(venta);
			}
			catch (Exception e) {
				// Display the cause. In a real system we would try harder to get a user-friendly message.
				ventaForm.recordError(e.getMessage());
			}
		}

		// PersonForm bubbles up SUCCESS or FAILURE when it is submitted, depending on whether VALIDATE records an error

		Object onSuccess() {
			return indexPage;
		}
		
}
